package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink16_TableAPI_OverWindow_EventTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - TableAPI — OverWindow（就是 类似 hive sql的 开窗函数 over(partition by order by preceding following) ）
        // 1.创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 2.将 流 转换成 Table
        Table table = tableEnv.fromDataStream(sensorDS, $("id"), $("ts"), $("vc"), $("et").rowtime());
        // TODO 3.使用 TableAPI 进行 OverWindow开窗
        Table resultTable = table
                .window(
                        Over
                                .partitionBy($("id"))
                                .orderBy($("et")) // orderby必须指定，而且必须是 时间字段
//                                .preceding(UNBOUNDED_ROW) // 上无边界，区分不同行
//                                .preceding(UNBOUNDED_RANGE)   // 上无边界，不区分不同行
//                                .preceding(lit(2).seconds())  // 往前 2s
                                .preceding(rowInterval(2L)) // 往前 2行
                                .as("ow")
                )
                .select($("id"), $("vc").sum().over($("ow")).as("vcSumByOver"));


        resultTable.execute().print();


        env.execute();
    }
}

/**
 */
